package fileServices;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import entities.CSFileWrapper;

public class FileReceiverService {
	private SSLServerSocket fileService;
	
	//Used for sending/reveiving a File(possibly abstract these methods to their own class
	public void startReceiveFileService() throws IOException{
		System.out.println("FileReceiverService: startReceiveFileService()");
		
		SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
		fileService = (SSLServerSocket) factory.createServerSocket(2083);
		fileService.setEnabledCipherSuites(fileService.getSupportedCipherSuites());
		
//		fileService = new ServerSocket(2083);
	}
	public void stopReceiveFileService() throws IOException{
		System.out.println("FileReceiverService: stopReceiveFileService()");
		fileService.close();
	}	
	public SSLSocket receiveFileConnection() throws IOException{
		System.out.println("FileReceiverService: receiveFileConnection()");
		SSLSocket client = (SSLSocket) fileService.accept();
		return client;
	}	
	
	public CSFileWrapper receiveFile(SSLSocket client, String fileName, int fileSize) throws IOException{
		System.out.println("FileReceiverService: receiveFile()");
		DataInputStream dis = new DataInputStream(client.getInputStream());
		
		byte[] fileData = new byte[fileSize];
		
		if(fileSize > 0){
			dis.readFully(fileData);
		}
		
		CSFileWrapper file = new CSFileWrapper();
		file.setData(fileData);
		file.setFileName(fileName);
		
		dis.close();		
		return file;
	}
	public void sendFile(byte[] data, InetAddress client) throws UnknownHostException, IOException{
		System.out.println("FileReceiverService: sendFile()");
		SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
		SSLSocket toClient = (SSLSocket) factory.createSocket(client, 2083);
		toClient.setEnabledCipherSuites(toClient.getSupportedCipherSuites());
		toClient.startHandshake();
//		Socket toClient = new Socket(client, 2083);
		
		OutputStream os = toClient.getOutputStream();
		DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
		dos.write(data);
		dos.flush();
		dos.close();
		toClient.close();
	}
}
